<?php

namespace App\Repository;

use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    public function getByPhone($phone)
    {
        return $this->findOneBy(array('phone' => $phone));
    }

    public function getByOpenid($openid)
    {
        return $this->findOneBy(array('openid' => $openid));
    }

    public function createSimpleData(User $user)
    {
        return array(
            "id" => $user->getId(),
            "name" => $user->getName(),
            "phone" => $user->getPhone(),
            "pic" => $user->getPic(),
            "apiToken" => $user->getApiToken()
        );
    }

    public function createNewUser($phone,$password,$openid="")
    {
        $user = new User();
        $user->setApiToken($phone)
            ->setPhone($phone)->setPic(DEFAULT_USER_HEAD)->setPassword(md5($password))
            ->setCreateAt(new \DateTime())
            ->setOpenid($openid)
            ->setIsOn(true)
            ->setName("用户$phone" ."_". rand(1000,9999));
        return $user;
    }
}
